package com.ruoyi.wx.service.imp;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.constant.ConstantWxBase;
import com.ruoyi.common.utils.XmlBean;
import com.ruoyi.system.domain.WxUser;
import com.ruoyi.system.service.WxUserService;
import com.ruoyi.wx.pojo.vo.CommonMsgVo;
import com.ruoyi.wx.pojo.vo.UserInfoVo;
import com.ruoyi.wx.service.WxAuthService;
import com.ruoyi.wx.service.WxMessageService;
import com.ruoyi.wx.service.WxUserWebService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class WxAuthServiceImp implements WxAuthService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private WxUserWebService wxUserWebService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private WxMessageService wxMessageService;

    @Override
    public Map<String, Object> getQr(String sceneId) {
        String accessToken = adminGetAccessToken();
        String formatUrl = String.format(ConstantWxBase.Url.GET_QR.getUrl(), accessToken);
        String result = HttpUtil.createPost(formatUrl)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .body("{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}").execute().body();
        return JSON.parseObject(result, new TypeReference<Map<String, Object>>() {
        }.getType());
    }

    @Override
    public String adminGetAccessToken() {
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        try {
            String accessToken = stringStringValueOperations.get("wx-admin-access_token");
            if (!"".equalsIgnoreCase(accessToken) && accessToken != null) return accessToken;
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        String formatUrl = String.format(ConstantWxBase.Url.GET_ACCESS_TOKEN.getUrl()
                , ConstantWxBase.Base.APP_ID.getVal()
                , ConstantWxBase.Base.SECRET.getVal());
        String result = HttpUtil.get(formatUrl);
        Map<String, Object> resultMap = JSON.parseObject(result, new TypeReference<Map<String, Object>>() {
        }.getType());
        String accessToken = resultMap.get("access_token").toString();
        stringStringValueOperations.set("wx-admin-access_token", accessToken, 7200, TimeUnit.SECONDS);
        return accessToken;
    }

    @Override
    public boolean isAuth(HttpServletRequest request) {

        return false;
    }

    @Override
    public void verificationMessage(HttpServletRequest httpServletRequest) {
        try {
            Map<String, String> stringStringMap = XmlBean.XmlToMap(httpServletRequest);
            System.out.println(stringStringMap);
            String event = stringStringMap.get("Event");
            if (!"subscribe".equalsIgnoreCase(event)) return;
            String userName = stringStringMap.get("FromUserName");
            String userId = stringStringMap.get("EventKey");
            if (userId == null || "".equalsIgnoreCase(userId)) {
                WxUser wxUser = new WxUser();
                wxUser.setOpenId(userName);
                List<WxUser> wxUsers = wxUserService.queryAll(wxUser);
                if (wxUsers.size() > 1) return;
            } else {
                String[] strings = userId.split("_");
                if (strings.length < 1) return;
                userId = strings[1];
                Integer integer = wxUserService.queryByUserId(strings[1]);
                if (integer == null) return;
                if (integer >= 1) return;
            }
            // Fong
            CommonMsgVo commonMsgVo = new CommonMsgVo();
            commonMsgVo.setTouser(userName);
            commonMsgVo.setMsgtype("text");
            CommonMsgVo.Text text = new CommonMsgVo.Text();
            text.setContent("登录成功");
            commonMsgVo.setText(text);
            wxMessageService.sendCommonMessage(commonMsgVo);
            Map<String, Object> userInfo = wxUserWebService.getUserInfo(Collections.singletonList(new UserInfoVo(userName, "zh_CN")));
            System.out.println(userInfo);
            List user_info_list = (List) userInfo.get("user_info_list");
            if (user_info_list.size() == 0) {
                log.error("用户信息没有获取到");
                return;
            }
            Map o = (Map) user_info_list.get(0);
            if ("0".equalsIgnoreCase(o.get("subscribe").toString())) {
                log.error("获取用户信息失败{}", userInfo);
                return;
            }
            WxUser wxUser = new WxUser();
            wxUser
                    .setNickname(o.get("nickname").toString())
                    .setOpenId(userName)
                    .setRemark(o.get("remark").toString())
                    .setSex(o.get("sex").toString())
                    .setSubscribeTime(o.get("subscribe_time").toString())
                    .setUserId(userId).setAvatar(o.get("headimgurl").toString());
            wxUserService.insert(wxUser);
            System.out.println(wxUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
